<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-operator" ref="popoverWrapperRef" v-clickOutside="hiddenPopover" >
          <a-row :gutter="42">  
            <a-col :md="17" :sm="7">
              <span class="table-page-search-submitButtons" :style="{ float: 'left', overflow: 'hidden' }">
                <a-button @click="popoverVisible = true" >筛选</a-button>
                <a-button type="primary"  @click="handleAdd">上传</a-button>
              </span>
            </a-col>
          </a-row>
          <div >
            <a-popover :getPopupContainer="getPopupContainer" placement="bottomRight" :visible="popoverVisible">
              <template #title>
                <!-- <CloseSquareOutlined @click="popoverVisible = false" /> -->
                <a-form class="div" ref="modalFormRef" :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                  <!-- <a-form-item label="版本号" class="item" name="versionNumber" :wrapper-col="{ span: 24, offset: 0 }">    -->
                  <a-form-item label="版本号" class="item" name="versionNumber">   
                    <a-input v-model="form.versionNumber" placeholder="请输入版本号" />
                  </a-form-item>
                  <a-form-item label="平台" class="item"  name="name" >          
                    <a-select v-model="form.tagNameId" :getPopupContainer="getPopupContainer" @change="getMemoryList">
                      <a-select-option :value="item.id" v-for="(item,index) in platformList" :key="index">{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="产物类型" class="item"  name="internalStorage" >
                    <a-select v-model="form.internalStorage" :getPopupContainer="getPopupContainer"
                      :disabled="!form.tagNameId" >
                      <a-select-option :value="item" v-for="(item,index) in memoryList" :key="index">{{item}}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="创建时间" class="item"  name="creationTime" >
                    <a-range-picker v-model="form.creationTime" :getCalendarContainer="getPopupContainer" />
                  </a-form-item>
                  <!-- <a-form-item required label="平台标识" name="tagSystem" >
                    <a-input v-model="form.tagSystem"/>
                  </a-form-item>
                  <a-form-item required label="产物类型" name="supports" >
                    <a-select mode="multiple" v-model="form.supports">
                      <a-select-option :value="item" v-for="(item,index) in memoryList" :key="index">{{item}}</a-select-option>
                    </a-select>
                  </a-form-item> -->
                </a-form>
              </template>
              <template #content>
                <a-button @click="formtoList">查询</a-button>
                <a-button @click="reformtoList">重置</a-button>
              </template>
            </a-popover>
          </div>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="supports" slot-scope="record">
          {{getSupportsTest(record)}}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">修改</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :mdlStatus="mdlStatus"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getRoleList, getServiceList } from '@/api/manage'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm';
import { getVersionsList, addVersion, delVersions, updateVersions, isExistVersion } from '@/api/versions';
import { mapActions } from 'vuex';
import { computeMD5 } from '@/utils/upload'
import { Modal } from 'ant-design-vue';
import { getTagNameList } from '@/api/platform'
import {
  CloseSquareOutlined,
} from '@ant-design/icons-vue';
import clickOutside from '@/core/directives/clickout';
import { sleep } from '@/utils/util';

const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber'
    // scopedSlots: { customRender: 'serial' }
  },
  {
    title: '平台',
    dataIndex: 'tagName'
    // dataIndex: 'name'
  },
  {
    title: '产物类型',
    dataIndex: 'internalStorage',
    // scopedSlots: { customRender: 'supports' }
  },
  {
    title: '版本',
    dataIndex: 'versionNumber'
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'msg'
  },
  {
    title: '版本说明',
    dataIndex: 'imprint'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    CloseSquareOutlined
  },
  directives: {clickOutside},
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        if(this.form.tagNameId) requestParameters.tagNameId = this.form.tagNameId
        if(this.form.internalStorage) requestParameters.internalStorage =`${this.form.internalStorage}`
        if(this.form.versionNumber) requestParameters.versionNumber = this.form.versionNumber
        if(this.form.startTime) requestParameters.startTime = moment(this.form.startTime).format('YYYY-MM-DD')
        if(this.form.endTime) requestParameters.endTime = moment(this.form.endTime).format('YYYY-MM-DD')
        return getVersionsList(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      
      platformList:[],
      memoryList:[0.5,1,1.5,2,3,4,6,8],
      form: {
        tagNameId:'',
        internalStorage:'',
        creationTime:[],
        versionNumber:'',

        startTime:'',
        endTime:'',
      },
      popoverVisible:false,
      mdlStatus:''
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.getPlatformList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    ...mapActions(['pushUploadItem', 'awaitSubmit']),
    formtoList(){
      if(this.form.creationTime.length){
        this.form.startTime = this.form.creationTime[0]
        this.form.endTime = this.form.creationTime[1]
      }
      this.popoverVisible = false
      this.$refs.table.refresh()
    },
    reformtoList(){
      this.form = {
        tagNameId:'',
        internalStorage:'',
        creationTime:[],
        versionNumber:'',
        startTime:'',
        endTime:'',
      }
      this.popoverVisible = false
      this.$refs.table.refresh()
    },
    async getPlatformList(){
      let param = {
        pageNum:1,
        pageSize:50,
      }
      const {data} = await getTagNameList(param)
      if(data.data){
        console.log('%c [ data.data ]-264', 'font-size:13px; background:pink; color:#bf2c9f;', data.data)
        for (let i = 0; i < data.data.length; i++) {
          this.platformList.push(data.data[i])
        }
      }
    },
    getMemoryList(e){
      const findData = this.platformList.find(i=> i.id == e);
      this.memoryList = JSON.parse( findData.supports) 
      this.form.internalStorage = ''
    },
    // getMemoryOptions(platformId) {
    //   const findData = this.platformOptions.find(i=> i.value == platformId);
    //   return findData?.memoryOptions;
    // },
    getSupportsTest(e){
      if(!e || !e.length) return '-'
      let text = ''
      let arr = JSON.parse(e)
      for (let i = 0; i < arr.length; i++) {
        text += `${arr[i]}`
        if(i < arr.length-1){
          text += '、'
        }
      }
      return text
    },
    handleAdd () {
      this.mdl = null
      this.mdlStatus = 'add'
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdlStatus = 'edit'
      this.mdl = { ...record }
    },
    handleDel (record) {
      let _self = this
      this.confirmLoading = true
      Modal.confirm({
        title: `确定删除 产物类型:${record.internalStorage} 版本:${record.versionNumber} 的 ${record.tagName}吗？`,
        // icon: createVNode(ExclamationCircleOutlined),
        // content: createVNode('div', { style: 'color:red;' }, 'Some descriptions'),
        onOk() {
          console.log('OK');
          delVersions({id:record.id}).then((res)=>{
            if(res.data.status == 200){
              _self.$message.success(`删除成功`)
              _self.editVisible = false
              _self.$refs.table.refresh()
            }else{
              _self.$message.error(res.data.msg)
            }
          })
          _self.confirmLoading = false
        },
        onCancel() {
          console.log('Cancel');
          _self.confirmLoading = false
        },
        class: 'test',
      });

      // if (record.status !== 0) {
      //   this.$message.info(`${record.no} 订阅成功`)
      // } else {
      //   this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      // }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const id = values.id;
          // console.log("🚀 ~ file: TableList.vue:253 ~ form.validateFields ~ id:", id)
          const api = id > 0 ? updateVersions : addVersion;
          new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(async (res) => {
              const { resourcesPath } = values;
              const fileUid = resourcesPath?.file?.uid;
              const fileName = resourcesPath?.file?.name
              if(fileName) {
                const fileType = fileName.substring(fileName.lastIndexOf(".")+1)
                if(fileType != 'zip' && fileType != 'fup' ){
                  this.confirmLoading = false
                  this.$message.error('仅支持上传zip文件与fup文件!')
                  return
                }
              }
              
              const {data:{status:isExistStatus,msg:isExistMsg}} = await isExistVersion({
                internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
                tagNameId: values.tagNameId,
                versionNumber: values.versionNumber,
                id,
              })
              if(isExistStatus != 200){
                this.$message.error(isExistMsg)
                this.confirmLoading = false
                return
              }
              // 没有选择上传文件，直接请求新增接口
              if(!fileUid) {
                const {data:{status,msg}} = await api({
                  msg: values.msg,
                  internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
                  tagNameId: values.tagNameId,
                  versionNumber: values.versionNumber,
                  resourcesPath: values.resourcesPath,
                  id,
                  imprint: values.imprint
                },);
                if(status != 200){
                  this.$message.error(msg)
                  this.confirmLoading = false
                  return
                }
              } else {
                const uploadList = this.$store.getters?.getUploadList || {};
                const uploadKey = await computeMD5(resourcesPath?.file);
                this.awaitSubmit({
                  key: uploadKey,
                  data: {
                    msg: values.msg,
                    tagNameId: values.tagNameId,
                    versionNumber: values.versionNumber,
                    internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
                    md5: uploadKey,
                    resourcesPath: values.resourcesPath,
                    id,
                    imprint: values.imprint
                  }
                });
                await sleep(500);
                this.pushUploadItem({
                  file: resourcesPath?.file,
                  success: ()=> {
                    // 刷新表格
                    try {
                      this.$refs.table.refresh()
                    } catch (error) {
                    }
                  },
                  fail: (e)=> {
                    console.log("错误");
                    console.log(e);
                  }
                });
              }
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success(this.mdlStatus == 'add'?'新增成功':'修改成功')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    getPopupContainer() {
      return this.$refs.popoverWrapperRef;
    },
    hiddenPopover() {
      this.popoverVisible = false;
    }
  }
}
</script>
<style>
  .div{
    width: 400px;
    margin: 20px;
  }
  .item{
    margin-bottom: 10px ;
  }
</style>